import 'package:FineArt/components/rounded_input_field.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/page/home/search_result.dart';
import 'package:FineArt/page/search/SearchServices.dart';
import 'package:FineArt/page/search/component/TextTagWidget.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:flutter/material.dart';

///搜索主页面
class SearchMainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _SearchMain();
  }
}

class _SearchMain extends State<SearchMainPage> {
  List<Widget> itemWidgetList = [];
  List<Widget> itemSearchList = [];
  List<GlobalSearch> globalSearchList = [];

  @override
  void setState(fn) {
    // TODO: implement setState
    super.setState(fn);
  }

  bool isSearch = false;
  String _searchKey;

  TextEditingController textEditingController = new TextEditingController();

  void search(String keyword) {
    SearchServices.setHistoryData(keyword);
    ModuleApi().globalSearch(keyword).then((res) {
      if (res.code == 200) {
        setState(() {
          globalSearchList.clear();
          itemWidgetList.clear();
        });
        if (res.data != null && res.data.length > 0) {
          globalSearchList.addAll(res.data);
          getTagList();
        }
      }
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    historySelection.clear();
    _getHistoryData();
  }

  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;
    return Scaffold(
      body: Container(
        margin: EdgeInsets.fromLTRB(getPortraitSWidth(11), getPortraitSHeight(30), 0, 0),
        decoration: BoxDecoration(color: Colors.white),
        alignment: Alignment.centerLeft,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                RoundedInputField(
                  icon: Image.asset(
                    "assets/images/icon_search.png",
                    width: getPortraitSWidth(16.5),
                    height: getPortraitSHeight(16.5),
                  ),
                  keyType: TextInputType.text,
                  hintText: "搜索素材",
                  height: getPortraitSHeight(33),
                  // width: double.infinity,
                  onChanged: (value) {
                    LogUtil.d("search val $value");
                    _searchKey = value;
                    setState(() {
                      isSearch = value.isEmpty ? false : true;
                    });
                  },
                  controller: textEditingController,
                ),
                InkWell(
                    onTap: () {
                      if (isSearch) {
                        search(_searchKey);
                        textEditingController.clear();
                        FocusScope.of(context).unfocus(); // dismiss keyboard
                        setState(() {
                          isSearch = false;
                        });

                        historySelection.clear();
                        _getHistoryData();
                      } else {
                        Navigator.of(context).pop();
                      }
                    },
                    child: Padding(
                      padding:
                          EdgeInsets.only(top: 2, left: getPortraitSWidth(20)),
                      child: Text(
                        isSearch ? "搜索" : "取消",
                        style: TextStyle(
                          fontSize: setSp(15),
                          color: red_text,
                        ),
                      ),
                    ))
              ],
            ),
            Container(
              width: size.width,
              height: size.height - getPortraitSHeight(100),
              child: ListView(
                shrinkWrap: true,
                padding: EdgeInsets.zero,
                children: [
                  if (globalSearchList.isNotEmpty)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Text(
                          "猜您想要",
                          style: TextStyle(
                              fontSize: setSp(18),
                              color: text_black,
                              fontWeight: FontWeight.normal),
                        ),
                        SizedBox(
                          height: getPortraitSHeight(12),
                        ),
                        Wrap(
                          children: itemWidgetList,
                          spacing: 5,
                          runSpacing: 10,
                        ),
                        SizedBox(
                          height: 40,
                        ),
                      ],
                    ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      InkWell(
                        onTap: () {
                          LogUtil.d("fold>>>>>");
                        },
                        child: Text(
                          "历史搜索",
                          style: TextStyle(
                              fontSize: setSp(18),
                              color: text_black,
                              fontWeight: FontWeight.normal),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 8),
                        child: InkWell(
                          child:Image.asset(
                            "assets/images/icon_garbage.png",
                            width: getPortraitSWidth(16),
                            height: getPortraitSHeight(16),
                          ),
                          onTap: () {
                            LogUtil.d("delete>>>>>");
                            if (mounted) {
                              setState(() {
                                SearchServices.removeHistoryList();
                                itemSearchList = [];
                              });
                            }
                          },
                        ),
                      )
                    ],
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Wrap(
                    children: itemSearchList,
                    spacing: 5,
                    runSpacing: 10,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  void getTagList() {
    setState(() {
      for (int i = 0; i < globalSearchList.length; i++) {
        GlobalSearch gs = globalSearchList[i];
        itemWidgetList.add(TextTagWidget(
          text: gs.fulllabel,
          fontSize: setSp(13),
          selected: gs.selected,
          color: gs.selected ? Colors.white : text_black,
          bgColor: gs.selected ? Colors.red : bg_input,
          index: i,
          textClick: (text, index) {
            for (GlobalSearch gs1 in globalSearchList) {
              gs1.selected = false;
            }
            globalSearchList[index].selected = true;
            itemWidgetList.clear();
            getTagList();
            SearchResultPage.showSearchResult(gs.path, gs.fulllabel, context);
          },
        ));
      }
    });
  }

  List<bool> historySelection = [];

  List<TextTagWidget> getSearchList(List history) {
    List<TextTagWidget> tList = [];
    for (var i = 0; i < history.length; i++) {
      historySelection.add(false);
      tList.add(TextTagWidget(
          text: history[i],
          selected: historySelection[i],
          color: historySelection[i] ? Colors.white : text_black,
          bgColor: historySelection[i] ? Colors.red : bg_input,
          fontSize: setSp(13),
          index: i,
          textClick: (text, index) {
            for (int j = 0; j < historySelection.length; j++) {
              historySelection[j] = false;
            }
            historySelection[index] = true;
            _getHistoryData();
            search(text);
          }));
    }
    return tList;
  }

  _getHistoryData() async {
    var history = await SearchServices.getHistoryList();
    setState(() {
      itemSearchList = getSearchList(history);
    });
  }
}
